import axios from 'axios'
import Utils from '@/utils/utils'
import { getStorage } from '@/utils/lib'

// 创建 axios 实例
axios.defaults.withCredentials = true

// 状态码
const CODE_URI = {
    200: '成功！',
    400: '错误请求！',
    401: '鉴权失败！',
    403: '服务器拒绝请求！',
    405: '验证码错误！',
    404: '服务器未找到请求！',
    500: '服务器发生错误'
}

const service = axios.create({
    // 接口请求的前缀
    baseURL: process.env.VUE_APP_BASE_API,

    // 接口请求超时时间
    timeout: 10000
})

// 无需鉴权的接口
const noAuth = [
    "/login",
    "/logout"
]


// 请求拦截
service.interceptors.request.use(config => {
    if (noAuth.indexOf(config.url) === -1) {
        config.headers['Authorization'] = 'Bearer ' + getStorage('token')
    }

    return config
}, error => {
    console.log(error)
})


// 响应拦截
service.interceptors.response.use(response => {
    let code = response.data.code

    if (code !== 200) {
        Utils.popUpMsg('error', response.data.msg, 3000)
        return Promise.reject(response.data)
    }

    return response.data
}, error => {
    let code = error.code

    Utils.popUpMsg('error', CODE_URI[code] || error.msg, 3000)
})



export default service
